<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/7/12
 * Time: 19:07
 */

namespace app\home\controller;


use app\common\model\Settings;
use app\common\model\Utils;

class User extends Common
{

    protected function _initialize()
    {
        parent::_initialize();
        if(!session("user_id")){
            $this->redirect("Index/login");
        }
    }

    public function index()
    {
        $this->templateTitle("个人中心");
        $user = \app\common\model\User::exists(session('user_id'));
        $this->assign("user", $user);
        //获取客服电话
        $system_setting = Settings::getSettings("key_global");
        $this->assign("server_tel", $system_setting["server_tel"]);
        return $this->fetch("index");
    }

    /**
     * 收获地址列表
     */
    public function address()
    {
        $this->templateTitle("收货地址");
        $list = \app\common\model\User::getAddressList(session("user_id"));
        $this->assign("list", $list);
        $redirect_url = input("redirect_url") ?: "";
        $this->assign("redirect_url", $redirect_url);
        return $this->fetch("address");
    }

    /**
     * 添加收获地址
     */
    public function addAddress()
    {
        $this->templateTitle("添加地址");
        if (request()->isAjax()) {
            try {
                $data = input("post.");
                $data["update_time"] = time();
                $data["uid"] = session("user_id");
                if ($data["is_def"] == 1) {
                    db("user_address")->where("uid", session("user_id"))->update(["is_def" => 0]);
                }
                $res = db("user_address")->insert($data);
                $this->ajaxSuccess("添加成功");
            } catch (\Exception $e) {
                $this->ajaxError($e->getMessage());
            }
        }
        $redirect_url = input("redirect_url") ?: "";
        $this->assign("redirect_url", $redirect_url);
        $this->assign("region", json_encode(Utils::getRegion()));
        return $this->fetch("addAddress");
    }

    /**
     * 编辑收获地址
     */
    public function editAddress()
    {
        $this->templateTitle("编辑地址");
        if (request()->isAjax()) {
            try {
                $data = input("post.");
                $data["update_time"] = time();
                $address_id = $data["address_id"];
                unset($data["address_id"]);
                if ($data["is_def"] == 1) {
                    db("user_address")->where("id", "neq", $address_id)->where("uid", session("user_id"))->update(["is_def" => 0]);
                }
                $res = db("user_address")->where("id", $address_id)->update($data);
                $this->ajaxSuccess("添加成功");
            } catch (\Exception $e) {
                $this->ajaxError($e->getMessage());
            }
        }
        $address_id = input("address_id");
        $redirect_url = input("redirect_url") ?: "";
        $address = db("user_address")->where("id", $address_id)->find();
        if (empty($address)) {
            echo "<script>history.back()</script>";
            exit;
        }
        $address["procity"] = \app\common\model\User::getProCity($address);
        $this->assign("address", $address);
        $this->assign("redirect_url", $redirect_url);
        $this->assign("region", json_encode(Utils::getRegion()));
        return $this->fetch("editAddress");
    }

    /**
     * 删除收获地址
     */
    public function delAddress()
    {
        $address_id = input("address_id");
        $res = db("user_address")->where("id", $address_id)->delete();
        if ($res) {
            $this->ajaxSuccess("删除成功");
        } else {
            $this->ajaxError("删除失败");
        }
    }

    /**
     * 下单处选择收获地址
     */
    public function selectAddress()
    {
        $redirect_url = input("redirect_url") ?: "";
        $address_id = input("address_id");
        $address = db("user_address")->where("id", $address_id)->find();
        if (!empty($redirect_url)) {
            $address["procity"] = \app\common\model\User::getProCity($address);
            session("address", $address);
            $this->redirect(base64_decode($redirect_url));
        }
    }

    /**
     * 积分消费记录
     */
    public function scoreLog()
    {
        $this->templateTitle("积分明细");
        $list = db("score_log")->where("uid", session("user_id"))->order("create_time desc")->select();
        $this->assign("list", $list);
        $this->assign("user", \app\common\model\User::exists(session("user_id")));
        return $this->fetch("score_log");
    }

    /**
     * 我的收藏
     */
    public function myFavorite()
    {
        if (request()->isAjax()) {
            $page = input("page") ?: 1;
            $page_num = input("page_num") ?: 20;
            $list = \app\common\model\Goods::myCollect(session("user_id"), $page, $page_num);
            $this->ajaxSuccess("请求成功", $list);
        }
        $this->templateTitle("我的收藏");
        return $this->fetch("favorite");
    }

    /**
     * 删除收藏
     */
    public function delCollect()
    {
        $gc_id = input("ids");
        db("goods_collection")->whereIn("id", explode(",", $gc_id))->delete();
        $this->ajaxSuccess("删除成功");
    }

    /**
     * 设置
     */
    public function setting()
    {
        $this->templateTitle("设置");
        $user = \app\common\model\User::exists(session("user_id"));
        $this->assign("user", $user);

        return $this->fetch("setting");
    }

    public function setAvatar()
    {
        $img_url = input("img_url");
        db("user")->where("id", session("user_id"))->update(["avatar" => $img_url]);
        $this->ajaxSuccess("设置成功");
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session("user_id", null);
        cookie("user_id", null);
        $this->redirect("Index/index");
    }

    /**
     * 关于我们
     */
    public function aboutUs()
    {
        $this->templateTitle("关于我们");
        //获取网站名称
        $system_setting = Settings::getSettings("key_global");
        $this->assign("system_title", $system_setting["system_title"]);
        $this->assign("about_us", Settings::getSettings("key_about_us"));
        return $this->fetch("about_us");

    }

    /**
     * 用户签到
     */
    public function sign()
    {
        $res = db("user_sign_log")->where("uid", session("user_id"))->where("create_time", "gt", strtotime(date("Y-m-d")))->find();
        if ($res) {
            $this->ajaxError("今日已签到");
        } else {
            $rate = db("rate")->find();
            //上次签到日期
            $pre = db("user_sign_log")->where("uid", session("user_id"))->order("id desc")->find();
            $pre_time = strtotime(date("Y-m-d", time() - 7 * 24 * 60 * 60));
            if ($pre_time < $pre["create_time"]) {
                $num = $pre["continuous_sign"] + 1;
            } else {
                $num = 1;
            }
            db("user_sign_log")->insert([
                "uid" => session("user_id"),
                "create_time" => time(),
                "score" => $rate["sign_normal"],
                "continuous_sign" => $num
            ]);
            //记录积分变动信息
            db("score_log")->insert([
                "uid" => session("user_id"),
                "type" => 1,
                "score" => $rate["sign_normal"],
                "content" => "签到赠送积分",
                "create_time" => time()
            ]);
            db("user")->where("id", session("user_id"))->setInc("score", $rate["sign_normal"]);
            db("user")->where("id", session("user_id"))->update(["last_sign_time"=>time(), "continuous_sign"=>$num]);
            $this->ajaxSuccess("签到成功");
        }

    }

    /**
     * 签到记录
     */
    public function sign_log()
    {
        $this->templateTitle("我的签到");
        $list = db("user_sign_log")->where("uid", session("user_id"))->order("create_time desc")->select();
        $this->assign("list", $list);
        return $this->fetch("sign_log");
    }

    public function modify_nick()
    {

        $this->templateTitle("修改昵称");
        if (request()->isAjax()) {
            $nick_name = input("nick_name");
            if (empty($nick_name)) {
                $this->ajaxError("昵称不能为空");
            }
            $res = db("user")->where("id", session("user_id"))->update(["nick_name" => $nick_name]);
            if ($res) {
                $this->ajaxSuccess("修改成功");
            } else {
                $this->ajaxError("修改失败");
            }
        }
        $this->assign("user", \app\common\model\User::exists(session("user_id")));

        return $this->fetch("modify_nick");
    }

    public function modify_password()
    {
        $this->templateTitle("修改密码");
        if (request()->isAjax()) {
            $data = input("post.");
            if (empty($data["pwd"]) || empty($data["pwd1"]) || empty($data["pwd2"])) {
                $this->ajaxError("密码不能为空");
            }
            $user = \app\common\model\User::exists(session("user_id"));
            if ($user["password"] != encrypt_user_password($data["pwd"])) {
                $this->ajaxError("原密码错误");
            }
            $res = db("user")->where("id", session("user_id"))->update(["password" => encrypt_user_password($data['pwd1'])]);
            if ($res) {
                $this->ajaxSuccess("修改成功");
            } else {
                $this->ajaxError("修改失败");
            }
        }

        return $this->fetch("modify_password");
    }


}